package com.example.luozizhao.eprxdemo.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

import com.example.luozizhao.eprxdemo.commom.App;
import com.example.luozizhao.eprxdemo.db.LocalDbHelper;
import com.example.luozizhao.eprxdemo.net.bean.ConactsBean;
import com.example.luozizhao.eprxdemo.net.bean.WaterMarkBean;
import com.example.luozizhao.eprxdemo.net.response.login.StationInfo;
import com.example.luozizhao.eprxdemo.net.response.login.UserLoginRespBean;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

/**
 * SharedPreference管理实体
 * @author yekaihe
 *
 */
public class SPManager {
	/** 全局：APP系统项 */
	private static final String SPG_APP = "tower_global_app";
	
	/** 全局：当前登录账号相关信息，仅切换用户时清空 */
	private static final String SPG_LOGIN = "tower_global_login";
	
	/** 全局：设置 */
	private static final String SPG_SETTING = "tower_global_setting";
	
	/** 用户级：系统项增加用户id的后缀 */
	private static String SP_SYSTEM = "tower_system";
	
	/** 用户级：会话项 */
	private static String SP_COOKIE = "tower_cookie";
	
	/** 用户级：基本项 */
	private static String SP_PROFILE = "tower_profile";
	
	/** 用户级：基本项 */
	private static String SP_PRIVILEGE = "tower_privilege";
	
	/** 用户级：基本项 */
	private static String SP_CHECKIN = "tower_checkin";
	
	private static String SP_PATROL = "tower_patrol";
	
	private static String SP_HOMEPAGE = "tower_homepage";
	
	private static String SP_LOCATION = "tower_location";

	/**
	 * 存储用户打开预案群聊界面的信息
 	 */
	private static String SP_EM_CHAT="transit_em_chat_info";

//	private static String SP_LOGIN = "uNamePwdSP";
//	private static String SP_CHECK = "last_hitcard_time";
//	private static String SP_CHECK_AUTO = "auto_checkin";
	
	/** 全局：APP系统项 */
	public static SPManager app;
	
	/** 全局：当前登录账号相关信息 */
	public static SPManager login;
	
	/** 全局：设置 */
	private static SPManager setting;
	
	/** 用户级：系统项 */
	public static SPManager system ;
	
	/** 用户级：会话项，存储seesion，token等信息 */
	public static SPManager cookie ;
	
	/** 用户级：基本项 */
	public static SPManager profile ;
	
	public static SPManager privilege;
	
	/** 用户级：打卡信息 */
	public static SPManager checkin ;
	
	/** 巡逻 */
	private static SPManager patrol;
	
	/** 首页 */
	private static SPManager homePage;
	
	/** 定位 */
	private static SPManager location;
	/** 定位 */
	public static SPManager emergency;
	
	/**
	 * 系统初始化设置
	 * */
	private static Context context;


	/**
	 * SharedPreferences实体
	 */
	private SharedPreferences sp;
	
	/** sp库名称 */
	private String spFileName;
	
	/**
	 * 私有构造方法
	 * @param spName
	 */
	private SPManager(String spName){
		this.spFileName = spName;
		
		if(context == null){
			context = com.example.luozizhao.eprxdemo.commom.App.applicationContext;
		}
		this.sp = context.getSharedPreferences(spFileName, Context.MODE_PRIVATE);
	}
	
	/**
	 * Application初始化
	 * 
	 * @param ctx
	 */
	public static void initAppLevel(Context ctx) {
		context = ctx;

		//系统级SharePerference
		app = new SPManager(SPG_APP);
		login = new SPManager(SPG_LOGIN);
		setting = new SPManager(SPG_SETTING);
		
		//用户级
		system = new SPManager(SP_SYSTEM);
		cookie = new SPManager(SP_COOKIE);
		profile = new SPManager(SP_PROFILE);
		privilege = new SPManager(SP_PRIVILEGE);
		checkin = new SPManager(SP_CHECKIN);
		patrol = new SPManager(SP_PATROL);
		homePage = new SPManager(SP_HOMEPAGE);
		location = new SPManager(SP_LOCATION);
		emergency=new SPManager(SP_EM_CHAT);

	}
	
//	/**
//	 * 登录成功后初始化
//	 * @param ctx
//	 */
//	public static void initUserLevel(Context ctx, int uid){
//		Field[] fields = SPManager.class.getDeclaredFields();
//		for (Field field : fields) {
//			String name = field.getName();
//			if (name.startsWith("SP_") && (field.getModifiers() & Modifier.PRIVATE) != 0
//					&& (field.getModifiers() | Modifier.STATIC) != 0 ) {
//				// 为app使用的SharedPreferences文件
//				try {
//					String spName = (String) field.get(null);
//					//添加用户ID
//					if(spName.startsWith("tower")){
//						field.set(null, uid + "_" +spName);
//					}
//				} catch (Exception e) {
//					// 获取失败，则跳过
//				}
//			}
//		}
//		
//		//用户级SP初始化，增加UID左后后缀
//		system = new SPManager(SP_SYSTEM);
//		cookie = new SPManager(SP_COOKIE);
//		profile = new SPManager(SP_PROFILE);
//		checkin = new SPManager(SP_CHECKIN);
//	}
	
	
	/**
	 * 清理场景：
	 * 场景1：用户退出（被T），无清理。设置强制手动登录标记
	 * 场景2：版本升级（清理所有用户级SP，登录账号不清理）
	 * 场景2：用户切换（清理登录账号信息，用户级SP不清理）
	 */
	
	/**
	 * 清除所有在本类中使用'SP_'命名的常量SharedPreferences
	 */
	public static void clear(Context context) {
		Field[] fields = SPManager.class.getDeclaredFields();
		for (Field field : fields) {
			String name = field.getName();
			if (name.startsWith("SP_") && (field.getModifiers() & Modifier.PRIVATE) != 0
					&& (field.getModifiers() | Modifier.STATIC) != 0) {
				// 为app使用的SharedPreferences文件
				try {
					String spName = (String) field.get(null);
					SharedPreferences sp = context.getSharedPreferences(spName, Context.MODE_PRIVATE);
					Editor editor = sp.edit();
					editor.clear();
					editor.commit();
				} catch (Exception e) {
					// 获取失败，则跳过
				}
			}
		}
	}
	
	/**
	 * 返回存储对象自己调用
	 * @return
	 */
	public SharedPreferences getSp(){
		return this.sp;
	}
	
	/**
	 * 设置存储对象
	 * @param key
	 * @param object
	 */
	public void put(String key, Object object) {
		SharedPreferences.Editor editor = sp.edit();
		if (object instanceof String) {
			editor.putString(key, (String) object);
		} else if (object instanceof Integer) {
			editor.putInt(key, (Integer) object);
		} else if (object instanceof Boolean) {
			editor.putBoolean(key, (Boolean) object);
		} else if (object instanceof Float) {
			editor.putFloat(key, (Float) object);
		} else if (object instanceof Long) {
			editor.putLong(key, (Long) object);
		} else {
			editor.putString(key, object.toString());
		}

		//apply提交，非commit
		editor.apply();
	}

	/**
	 * 获取值
	 * @param key
	 * @param defValue
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public <T> T get(String key, T defValue) {
		Object value = null;
		if (defValue instanceof String) {
			value = sp.getString(key, (String) defValue);
		} else if (defValue instanceof Integer) {
			value = sp.getInt(key, (Integer) defValue);
		} else if (defValue instanceof Boolean) {
			value = sp.getBoolean(key, (Boolean) defValue);
		} else if (defValue instanceof Float) {
			value = sp.getFloat(key, (Float) defValue);
		} else if (defValue instanceof Long) {
			value = sp.getLong(key, (Long) defValue);
		}

		//类型转换
		if(value != null){
			return (T)value;
		} else {
			return null;
		}
	}




	/**
	 * 简单数据设置（String）
	 * @param key
	 * @param value
	 */
	public void putString(String key, String value){
		SharedPreferences.Editor editor = sp.edit();
		editor.putString(key, value);
		editor.apply();
	}

	/**
	 * 简单数据设置（int）
	 * @param key
	 * @param value
	 */
	public void putInt(String key, int value){
		SharedPreferences.Editor editor = sp.edit();
		editor.putInt(key, value);
		editor.apply();
	}

	/**
	 * 简单数据设置（long）
	 * @param key
	 * @param value
	 */
	public void putLong(String key, long value){
		SharedPreferences.Editor editor = sp.edit();
		editor.putLong(key, value);
		editor.apply();
	}

	/**
	 * 简单数据设置（boolean）
	 * @param key
	 * @param value
	 */
	public void putBoolean(String key, boolean value){
		SharedPreferences.Editor editor = sp.edit();
		editor.putBoolean(key, value);
		editor.apply();
	}

	/**
	 * 简单数据设置（float）
	 * @param key
	 * @param value
	 */
	public void putFloat(String key, float value){
		SharedPreferences.Editor editor = sp.edit();
		editor.putFloat(key, value);
		editor.apply();
	}

	/**
	 * TODO 暂时有缺陷，待修复
	 * @param bean
	 */
    public <B> void putBean(B bean){
    	Editor editor = sp.edit();

		Class<?> clz=bean.getClass();
		Field[] fields=clz.getDeclaredFields();
		for(Field field:fields){
			field.setAccessible(true);
			String name=field.getName();
			Object value = null;
			try {
				value = field.get(bean);
			} catch (Exception e) {
			}

			//执行更新，Null字段不处理
			if(value != null){
				put(field.getType(), name, value, editor);
			}
		}

		//提交
		editor.apply();
    }

    /**
     * 写入或者修改属性（不提交）
     * @param fieldType
     * @param name
     * @param value
     * @param editor
     */
    private void put(Class<?> fieldType, String name, Object value, Editor editor){
		//原生类型
		if (fieldType.isPrimitive()) {
			char primitiveType =fieldType.getName().charAt(0);
			switch (primitiveType) {
			case 'I':
				editor.putInt(name, (Integer) value);
				break;
			case 'J':
				editor.putLong(name, (Long) value);
				break;
			case 'F':
				editor.putFloat(name, (Float) value);
				break;
			case 'Z':
				editor.putBoolean(name, (Boolean) value);
				break;
			default:
				editor.putString(name, String.valueOf(value));
				break;
			}
		} else if(fieldType == Integer.class){
			editor.putInt(name, (Integer) value);
		} else if(fieldType == Long.class){
			editor.putLong(name, (Long) value);
		} else if(fieldType == Float.class){
			editor.putFloat(name, (Float) value);
		} else if(fieldType == Boolean.class){
			editor.putBoolean(name, (Boolean) value);
		} else{
			editor.putString(name, String.valueOf(value));
		}
    }

    /**
     *
     * @author yekaihe
     *
     */
    public static class App{
    	public static final String SP_APP_VERSION_CODE = "app.version.code";
    	public static final String SP_APP_SESSION = "sessionId";

		/**
    	 * 获取最后上次登录的版本
    	 * @return
    	 */
    	public static int getLastAppVersionCode(){
    		return app.getSp().getInt(SP_APP_VERSION_CODE, 0);
    	}

    	/**
    	 * 更新最后登录的版本号
    	 * @param versionCode
    	 */
    	public static void updateLastAppVersionCode(int versionCode){
			//更新版本信息(使用commit，保证提交到文件)
			SharedPreferences.Editor editor = SPManager.app.getSp().edit();
			editor.putInt(SP_APP_VERSION_CODE, versionCode);
			editor.commit();
    	}

    	public static void setSessionId(String sessionId){
    		app.putString(SP_APP_SESSION, sessionId);
    	}

    	public static String getSessionId(){
    		return app.getSp().getString(SP_APP_SESSION, "");
    	}

    	public static int getDataVersion(String code){
    		return app.getSp().getInt(code,-1);
		}

		public static void setDataVersion(String code, int version){
			Editor edit = app.getSp().edit();
			edit.putInt(code,version);
			edit.commit();
		}

		public static String getFaceTip(String key){
			return app.getSp().getString(key,"下次询问");
		}

		public static void putFaceTip(String key, String value){
			Editor edit = app.getSp().edit();
			edit.putString(key,value);
			edit.commit();
		}
    }

    /**
     * 登录账户信息
     * @author yekaihe
     *
     */
    public static class Login{
    	public static void putLoginInfo(String user, String password) {
    		login.putString("user", user);
    		login.putString("password", password);

    		//设置自动登录
    		setManualLogin(false);
    	}

    	public static void setLoginPassword(String password){
    		SharedPreferences.Editor editor = login.getSp().edit();
    		editor.putString("password", password);
    		editor.commit();
    	}

    	public static String getLoginUser() {
    		return login.get("user", "");
    	}

    	public static String getLoginPassword() {
    		return login.get("password", "");
    	}

    	/**
    	 * 手动登录
    	 * @return
    	 */
    	public static boolean getManualLogin() {
    		return login.get("manualLogin", false);
    	}

    	/**
    	 * 设置手动登录
    	 * @return
    	 */
		public static void setManualLogin(boolean manualLogin) {
			login.putBoolean("manualLogin", manualLogin);
		}

		/**
		 * 设置环信登录信息
		 * @param user
		 * @param password
		 */
    	public static void putHxCountInfo(String user, String password) {
    		login.putString("hx.user", user);
    		login.putString("hx.password", password);
    	}



    	public static String getHxUser() {
    		return login.get("hx.user", "");
    	}

    	public static String getHxPassword() {
    		return login.get("hx.password", "");
    	}

    	public static void setFirstLoginTag(boolean isFirst){
    		Editor editor=login.getSp().edit();
    		editor.putBoolean("is_first_login",isFirst);
    		editor.commit();

		}

    	public static boolean getFirstLoginTag(){
    		return login.get("is_first_login", true);
		}
    }

    /**
     * 全局设置（多用户共享）
     * @author yekaihe
     *
     */
	public static class Setting {
		private static final String SHARED_KEY_SETTING_NOTIFICATION = "shared_key_setting_notification";
		private static final String SHARED_KEY_SETTING_SOUND = "shared_key_setting_sound";
		private static final String SHARED_KEY_SETTING_VIBRATE = "shared_key_setting_vibrate";
		private static final String SHARED_KEY_SETTING_SPEAKER = "shared_key_setting_speaker";

		public static void setSettingMsgNotification(boolean paramBoolean) {
			setting.putBoolean(SHARED_KEY_SETTING_NOTIFICATION, paramBoolean);
		}

		public static boolean getSettingMsgNotification() {
			return setting.getSp().getBoolean(SHARED_KEY_SETTING_NOTIFICATION, true);
		}

		public static void setSettingMsgSound(boolean paramBoolean) {
			setting.putBoolean(SHARED_KEY_SETTING_SOUND, paramBoolean);
		}

		public static boolean getSettingMsgSound() {

			return setting.getSp().getBoolean(SHARED_KEY_SETTING_SOUND, true);
		}

		public static void setSettingMsgVibrate(boolean paramBoolean) {
			setting.putBoolean(SHARED_KEY_SETTING_VIBRATE, paramBoolean);
		}

		public static boolean getSettingMsgVibrate() {
			return setting.getSp().getBoolean(SHARED_KEY_SETTING_VIBRATE, true);
		}

		public static void setSettingMsgSpeaker(boolean paramBoolean) {
			setting.putBoolean(SHARED_KEY_SETTING_SPEAKER, paramBoolean);
		}

		public static boolean getSettingMsgSpeaker() {
			return setting.getSp().getBoolean(SHARED_KEY_SETTING_SPEAKER, true);
		}
	}

    /**
     * 当前登录用户的基本信息
     * @author yekaihe
     *
     */
    public static class Profile{
    	/**
    	 * 存储登录基本信息
    	 * @param bean
    	 */
    	public static void setBasicData(UserLoginRespBean bean) {
    		SharedPreferences preferences = SPManager.profile.getSp();
    		Editor edit = preferences.edit();
    		edit.clear();
    		edit.commit();
    		UserLoginRespBean.Basic basic = bean.getData().getBasic();
    		edit.putInt("uid", basic.getUid());
    		edit.putString("emegencyTel", basic.getEmegencyTel());
    		edit.putInt("orgId", basic.getOrgId() == null ? -1 : basic.getOrgId());
    		edit.putString("idNumber", basic.getIdNumber());
    		edit.putString("mobile", basic.getMobile());
    		edit.putString("orgName", basic.getOrgName());
    		edit.putString("emegencyTel", basic.getEmegencyTel());
    		edit.putString("uname", basic.getUname());
    		edit.putString("avatar", basic.getAvatar());
    		edit.putString("hxPassword", basic.getHxPassword());
    		edit.putInt("type", basic.getType() == null ? -1 : basic.getType());
    		edit.putStringSet("gridList", bean.getData().getGridList());
    		//wuwenle 20160722 新增职位、人员类型
    		edit.putString("jobName", basic.getJobName());
    		edit.putInt("roleType", basic.getRoleType());

			//人脸的信息
			UserLoginRespBean.FaceInfo faceInfo = bean.getData().getFaceInfo();
			if(faceInfo != null) {
				edit.putString("faceId", faceInfo.getFaceId());
				edit.putString("faceUrl", faceInfo.getFaceUrl());
				edit.putString("companyId", faceInfo.getCompanyId());
			}

    		//设置考情信息
    		List<UserLoginRespBean.ScheduItemBean> scheduleList = bean.getData().getScheduleList();
    		if (scheduleList != null) {
    			for (UserLoginRespBean.ScheduItemBean scheduItem : scheduleList) {
    				TimeUtils.saveTimeToLocal(scheduItem, edit);
    			}
    		}
    		edit.commit();
    		// 保存登录的车站信息，放在commit后面，因为save的时候需要用到uid，必须在commit之后才有
    		List<StationInfo> stationList = bean.getData().getStationList();
    		if (stationList != null) {
    		    LocalDbHelper.getSystemInstance().clearAll(StationInfo.class);
    		    LocalDbHelper.getSystemInstance().save(stationList);
    		}
    		List<ConactsBean> friendList = bean.getData().getFriendList();
    		if (friendList != null) {
    		    LocalDbHelper.getSystemInstance().clearAll(ConactsBean.class);
                LocalDbHelper.getSystemInstance().save(friendList);
    		}
    	}

    	public static int getUid(){
    		return profile.getSp().getInt("uid", 0);
    	}

    	public static String getUname(){
    		return profile.getSp().getString("uname", "");
    	}

    	public static int getType(){
    		return profile.getSp().getInt("type", 0);
    	}


    	public static int getOrgId(){
    		return profile.getSp().getInt("orgId", 0);
    	}

    	public static String getOrgName(){
    		return profile.getSp().getString("orgName", "塔式支队");
    	}

    	public static String getAvatar(){
    		return profile.getSp().getString("avatar", "");
    	}

		public static void setAvatar(String avatar) {
			profile.putString("avatar", avatar);
		}

		public static String getIdNumber(){
			return profile.getSp().getString("idNumber", "");
		}


		public static void putAlarmStatus(boolean needDelay) {
			Editor editor=profile.getSp().edit();
			editor.putBoolean("needDelay", needDelay);
			editor.commit();
		}
		public static boolean getAlarmStatus() {
			return profile.getSp().getBoolean("needDelay",false);
		}

    	public static String getEmergencyTel(){
    		return profile.getSp().getString("emegencyTel", "85000055");
    	}

    	public static String getScheduleStartTime(){
    		return profile.getSp().getString("startTime", "");
    	}

    	public static String getScheduleEndTime(){
    		return profile.getSp().getString("endTime", "");
    	}

    	public static Long getScheduleDate(){
    		return profile.getSp().getLong("scheduleDate", 0);
    	}

    	public static Set<String> getGridList(){
    		return profile.getSp().getStringSet("gridList", null);
    	}

    	public static String getMobile(){
    		return profile.getSp().getString("mobile", "");
    	}
     	public static String getJobName(){
    		return profile.getSp().getString("jobName", "");
    	}
     	public static int getRoleType(){
    		return profile.getSp().getInt("roleType", 0);
    	}

		public static void putOnlineStatus(int onlineStatus) {
			Editor editor=profile.getSp().edit();
			editor.putInt("onlineStatus", onlineStatus);
			editor.commit();
		}

		public static int getOnlineStatus() {
			return profile.getSp().getInt("onlineStatus", 0);
		}


		public static String getFaceUrl(){
			return profile.getSp().getString("faceUrl", "");
		}

		public static String getFaceId(){
			return profile.getSp().getString("faceId", "");
		}

		public static String getCompanyId(){
			return profile.getSp().getString("companyId", "");
		}

    	/** 通用的获取用户属性的方法 */
		public static <T> T getBasic(String prop, T defValue) {
			return profile.get(prop, defValue);
		}
    }

    /**
     * 用户级系统变量
     * @author yekaihe
     *
     */
    public static class SystemInfo{
    	private static final String MAX_INBOX_ID = "sys.inbox.maxid";
    	private static final String MAX_VERSION = "sys.notice.version";
    	private static final String MIN_DATE = "sys.notice.min.date";

    	public static void setInboxMaxId(long maxId){
    		system.put(MAX_INBOX_ID, maxId);
    	}

    	public static long getInboxMaxId(){
    		return system.get(MAX_INBOX_ID, 0L);
    	}

    	public static void setNoticeMaxVersion(Integer maxVersion){
    		system.put(MAX_VERSION, maxVersion);
    	}
		public static int getWaterMark(){
			return system.getSp().getInt("watermark", WaterMarkBean.TYPE_NO);
		}

		public static void setWaterMark(int type){
			SharedPreferences.Editor editor=system.getSp().edit();
			editor.putInt("watermark",type);
			editor.commit();
		}

    	public static Integer getNoticeMaxVersion(){
    		return system.get(MAX_VERSION, 0);
    	}

    	public static void setNoticeMinDate(long minDate){
    		system.put(MIN_DATE, minDate);
    	}

    	public static long getNoticeMinDate(){
    		return system.get(MIN_DATE, 0L);
    	}

    }

    /**
     * 打开相关信息
     * 班次信息表（本地清理两个月之前的数据，）
     * <hr>
     * 通用班次1：名称，类别(1)，开始时间，结束时间，工作地编号，失效日期，失效日期
     * 通用班次2：名称，类别(1)，开始时间，结束时间，工作地编号，生效日期，失效日期
     * 定制排班x：名称，类别(2)，开始时间，结束时间，工作地编号，生效日期
     * （每天第一次使用刷新，调班生效后刷新，班次变更后刷新，“我的排班”主动刷新操作，“系统设置”清空本地缓存数据）
     * <hr>
     * 巡逻轨迹表（用于本地查询和缓存）
     * ID，时间，经度，纬度，附加信息（）
     * SharePerference中记录上传的最大ID值
     *
     * 打卡表（用于本地查询）：
     * ID，时间，经度，纬度，附加信息，位置描述
     *
     * 区域表（如何更新）
     *
     * SH中保存最近一次的上班卡，和下班卡数据
     *
     * @author yekaihe
     *
     */
    public static class Checkin {
    	/**
    	 * 排班数据刷新时间
    	 * @param lastRefreshTime
    	 */
    	public static void setLastRefreshTime(long lastRefreshTime){
    		SharedPreferences.Editor editor = checkin.getSp().edit();
    		editor.putLong("lastRefreshDate", lastRefreshTime);
    		editor.commit();
    	}
    	
    	/**
    	 * 获取最后更新时间
    	 */
    	public static long getLastRefreshTime(){
    		return checkin.getSp().getLong("lastRefreshDate", 0);
    	}
    	
    	/**
    	 * 获取今天排班
    	 * @return
    	 */
    	public static long getShiftToday(){
    		//特定排班用1-7标识（星期几），通用班次用0来标识（）
    		int weekDay = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
    		return checkin.getSp().getLong("shift_" + weekDay, 0);
    	}
    	
    	/**
    	 * 获取前一天的排班
    	 * @return
    	 */
		public static long getShiftYesterday() {
			int weekDay = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
			if (weekDay == Calendar.SUNDAY) {
				weekDay = 7;
			} else {
				weekDay -= 1;
			}

			return checkin.getSp().getLong("shift_" + weekDay, 0);
		}
		
		/**
		 * 获取：昨天，今天和明天的排班
		 * @return
		 */
		public static long[] getShifts() {
			int today = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
			int yesterday = today - 1;
			if (yesterday == 0) {
				yesterday = 7;
			}

			int tomorrow = today + 1;
			if (tomorrow == 8) {
				tomorrow = 1;
			}

			long[] shifts = new long[3];
			shifts[0] = checkin.getSp().getLong("shift_" + yesterday, 0);
			shifts[1] = checkin.getSp().getLong("shift_" + today, 0);
			shifts[2] = checkin.getSp().getLong("shift_" + tomorrow, 0);

			return shifts;
		}
		
		/**
		 * 设置排班
		 * @param shifts
		 */
		public void setShifts(long[] shifts){
			int today = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
			int yesterday = today - 1;
			if (yesterday == 0) {
				yesterday = 7;
			}

			int tomorrow = today + 1;
			if (tomorrow == 8) {
				tomorrow = 1;
			}
			
			Editor edit = checkin.getSp().edit();
			if (shifts.length == 3) {
				if (shifts[0] != 0) {
					edit.putLong("shift_" + yesterday, shifts[0]);
				}
				if (shifts[1] != 0) {
					edit.putLong("shift_" + today, shifts[1]);
				}
				if (shifts[2] != 0) {
					edit.putLong("shift_" + tomorrow, shifts[2]);
				}
			} else if (shifts.length == 2) {
				if (shifts[0] != 0) {
					edit.putLong("shift_" + today, shifts[0]);
				}
				if (shifts[1] != 0) {
					edit.putLong("shift_" + tomorrow, shifts[1]);
				}
			}
			edit.apply();
		}
		
		/** 一周的时间长度 */
		private static final long sevenDay = 7*24*60*60*1000;
		public static void setShift(long day, String startTime, String endTime) {
			//时间不超出左右一周
			if (Math.abs(System.currentTimeMillis() - day) > sevenDay) {
				return;
			}
			
			Calendar c = Calendar.getInstance();
			c.setTimeInMillis(day);
			
			//week day
			int weekDay =c.get(Calendar.DAY_OF_WEEK);
			checkin.putString("shift_" + weekDay+"_start", startTime);
			checkin.putString("shift_" + weekDay+"_end", endTime);
		}
    	
    	/**
    	 * 记住自动签到记录（优化为通过表记录）
    	 */
    	public static void setAutoCheckInRecord(Set<String> records) {
    		Editor editor = checkin.getSp().edit();
    		editor.putStringSet("record", records);
    		editor.commit();
    	}
    	
    	/**
		 * 获取自动签到记录
		 */
		public static Set<String> getAutoCheckInRecord() {
			Set<String> record = checkin.getSp().getStringSet("record", new TreeSet<String>());
			if (!(record instanceof TreeSet)) {
				Set<String> treeSet = new TreeSet<String>();
				treeSet.addAll(record);
				record = treeSet;
			}
			return record;
		}

		/**
		 * 清空自动签到记录
		 */
		public static void clearAutoCheckInRecord() {
			Editor editor = checkin.getSp().edit();
			editor.remove("record");
			editor.commit();
		}
		
		/**
		 * 保留设置size为长度的Record
		 * @param size
		 */
		public static void clearRecordRetainSize(int size) {
			Set<String> newRecord = new TreeSet<String>();
			Set<String> record = getAutoCheckInRecord();
			if (record != null) {
				int begin = record.size() - size;
				Iterator<String> it = record.iterator();
				int i = 0;
				String element = null;
				while (it.hasNext()) {
					element = it.next();
					if (i >= begin) {
						newRecord.add(element);
					}
					i++;
				}
			}
			setAutoCheckInRecord(newRecord);
		}

//    	/**
//    	 * 获取下班打卡时间的sp
//    	 */
//    	public SharedPreferences getOffWorkHitcardTime() {
//    		SharedPreferences preferences = applicationContext
//    				.getSharedPreferences(LAST_HITCARD_TIME, applicationContext.MODE_PRIVATE);
//    		return preferences;
//    	}
    	
//    	/**
//    	 * 清空下班打卡时间的sp
//    	 */
//    	public void clearOffWorkHitcardTime() {
//    		SharedPreferences preferences = applicationContext
//    				.getSharedPreferences(LAST_HITCARD_TIME, applicationContext.MODE_PRIVATE);
//    		preferences.edit().clear().commit();
//    	}
    	
    	/**
    	 * 保存下班打卡时间
    	 */
    	public static void setOffWorkHitcardTime(Calendar c, boolean isXiaBanEarly) {
            int year = c.get(Calendar.YEAR);
            int month = c.get(Calendar.MONTH);
            int day = c.get(Calendar.DAY_OF_MONTH);
            int hour = c.get(Calendar.HOUR_OF_DAY);
            
    		Editor edit = checkin.sp.edit();
    		edit.putInt("year", year);
    		edit.putInt("month", month);
    		edit.putInt("day", day);
    		edit.putInt("hour", hour);
    		edit.putBoolean("isXiaBanEarly", isXiaBanEarly);
    		edit.commit();
    	}
    	
    	public static Boolean isXiaBanEarly(Long begin, Long end) {
    		Boolean result = false;
    		Boolean isXiaBanEarly = checkin.getSp().getBoolean("isXiaBanEarly", false);
    		if (isXiaBanEarly) {
    			Calendar c = Calendar.getInstance();
    			Integer year = checkin.getSp().getInt("year", 0);
    			Integer month = checkin.getSp().getInt("month", 0);
    			Integer day = checkin.getSp().getInt("day", 0);
    			Integer hourOfDay = checkin.getSp().getInt("hour", 0);
    			Integer minute = 0;
    			c.set(year, month, day, hourOfDay, minute);
    			if (c.getTime().getTime() > begin && c.getTime().getTime() < end) {
    				result = true;
    			}
    		}
    		return result;
    	}
    	
  /*  	public static Boolean isXiaBan(Long end){
    		Boolean result = false;
    		Calendar c = Calendar.getInstance();
			Integer year = checkin.getSp().getInt("year", 0);
			Integer month = checkin.getSp().getInt("month", 0);
			Integer day = checkin.getSp().getInt("day", 0);
			Integer hourOfDay = checkin.getSp().getInt("hour", 0);
			Integer minute = 0;
			c.set(year, month, day, hourOfDay, minute);
			Long time = c.getTime().getTime();
    		if (time > end && time < end + AttendanceModelHelper.TWO_HOUR_MS) {
    			result = true;
    		}
    		return result;
    	}*/
    	
    	/**
    	 * 获取打卡时间
    	 */
    	public static long getCheckInTime() {
    		return checkin.getSp().getLong("checkInTimeMills", 0);
    	}
    	
//    	/**
//    	 * 清空打卡时间
//    	 */
//    	public void clearCheckInTime() {
//    		SharedPreferences preferences = applicationContext
//    				.getSharedPreferences(CHECKIN_TIME, applicationContext.MODE_PRIVATE);
//    		preferences.edit().clear().commit();
//    	}
    	
    	/**
    	 * 保存打卡时间(单位毫秒)
    	 */
    	public static void setCheckInTime(long checkInTimeMills) {
//    		SharedPreferences preferences = applicationContext
//    				.getSharedPreferences(CHECKIN_TIME, applicationContext.MODE_PRIVATE);
//    		Editor edit = preferences.edit();
    		checkin.putLong("checkInTimeMills", checkInTimeMills);
//    		edit.commit();
    	}
    }
    
    /**
     * 系统定位（缓存）
     * @author yekaihe
     *
     */
    public static class Location{
    	public static void setLocation(long time, double lat, double lng){
    		Editor edit = location.sp.edit();
    		edit.putLong("time", time);
    		edit.putLong("lat", Double.doubleToLongBits(lat));
    		edit.putLong("lng", Double.doubleToLongBits(lng));
    		edit.remove("addr");
    		edit.apply();
    	}
    	
    	public static void setLocation(long time, double lat, double lng, String addr){
    		Editor edit = location.sp.edit();
    		edit.putLong("time", time);
    		edit.putLong("lat", Double.doubleToLongBits(lat));
    		edit.putLong("lng", Double.doubleToLongBits(lng));
    		edit.putString("addr", addr);
    		edit.apply();
    	}
    	
    	/**
    	 * 返回带位置的地址
    	 * @param timeout
    	 * @return
    	 */
    	/*public static BDLocation getLocationWithAddr(int timeout){
    		if(!location.getSp().contains("addr")){
    			return null;
    		}
    		
    		long time = location.getSp().getLong("time", 0);
    		if(time==0 || System.currentTimeMillis() - time > timeout){
    			return null;
    		}
    		
    		BDLocation loc = new BDLocation();
    		loc.setLatitude( Double.longBitsToDouble(location.getSp().getLong("lat", 0)));
    		loc.setLongitude(Double.longBitsToDouble(location.getSp().getLong("lng", 0)));
    		loc.setAddrStr(location.getSp().getString("addr", ""));
    		return loc;
    	}
    	*/
    	/**
    	 * 返回定位信息，如果超过30秒，则返回null
    	 * @return 定位的纬度和经度（纬度在前），null则表示定位数据不存在或者过期
    	 */
    	public static double[] getLocation(){
    		//默认返回30S内的位置
    		return getLocation(30000);
    	}
    	
    	public static double[] getLocation(long timeout){
    		long time = location.getSp().getLong("time", 0);
    		if(time==0 || System.currentTimeMillis() - time > timeout){
    			return null;
    		}
    		
    		return new double[]{
    				Double.longBitsToDouble(location.getSp().getLong("lat", 0)),
    				Double.longBitsToDouble(location.getSp().getLong("lng", 0))};
    	}
    }
    
    /**
     * 巡逻信息
     * @author yekaihe
     *
     */
    public static class Patrol{
    	/**
    	 * 设置巡逻服务状态
    	 */
    	public static void setPatrolStatus(int status){
    		patrol.putInt("patrol.service.status", status);
    	}
    	
    	/**
    	 * 获取巡逻服务状态
    	 */
    	public static int getCurrentPatrol(){
    		return patrol.getSp().getInt("patrol.service.status", 0);
    	}
    	
    	public static void setCurrentPatrol(long patrolId){
    		
    	}
    	
    	public static void setPreviousLoc(){
    		
    	}

		public static void setGPSLocation(String loc) {
			
		}

		public static void saveBattery(int i) {
			// TODO Auto-generated method stub
			
		}

		public static void setSportsMode(int i) {
			
		}

		public static void setLocation(String location) {
			patrol.putString("location", location);
		}
		
		public static String getLocation(){
			return patrol.getSp().getString("location", "");
		}

		public static boolean getPatrolDebug() {
			return false;
		}

		public static boolean getSettingIsSavePower() {
			return false;
		}

		public static long getRunningRouteId() {
			return patrol.getSp().getLong("route.id", 0);
		}
		
		public static void setRunningRouteId(long routeId){
			patrol.putLong("route.id", routeId);
		}
    }
    
    /**
     * 
     * 首页提示信息
     * 
     * @author heenliang
     * @date 2016年10月13日
     * @version [版本号]
     * @see [相关类/方法]
     * @since [产品/模块版本]
     */
    public static class HomePage {
        public static Boolean hasWorkInfoTip() {
            return homePage.getSp().getBoolean("homepage.workinfo.tip", false);
        }

        public static void setWorkInfoTip(Boolean hasTip) {
            homePage.putBoolean("homepage.workinfo.tip", hasTip);
        }
        
        public static Boolean hasContactsTip() {
            return homePage.getSp().getBoolean("homepage.contacts.tip", false);
        }
        
        public static void setContactsTip(Boolean hasTip) {
            homePage.putBoolean("homepage.contacts.tip", hasTip);
        }
        
        public static Boolean hasStatisticsTip() {
            return homePage.getSp().getBoolean("homepage.statistics.tip", false);
        }
        
        public static void setStatisticsTip(Boolean hasTip) {
            homePage.putBoolean("homepage.statistics.tip", hasTip);
        }
        
        public static Boolean hasTaskTip() {
            return homePage.getSp().getBoolean("homepage.task.tip", false);
        }
        
        public static void setTaskTip(Boolean hasTip) {
            homePage.putBoolean("homepage.task.tip", hasTip);
        }
        
        public static Boolean hasNotificationTip() {
            return homePage.getSp().getBoolean("homepage.notification.tip", false);
        }
        
        public static void setNotificationTip(Boolean hasTip) {
            homePage.putBoolean("homepage.notification.tip", hasTip);
        }
        
        public static Boolean hasNewMessage() {
            return homePage.getSp().getBoolean("homepage.message.newmsg", false);
        }
        
        public static void setNewMessage(Boolean newMsg) {
            homePage.putBoolean("homepage.message.newmsg", newMsg);
        } 
        
        public static Long getMessageTime() {
            return homePage.getSp().getLong("homepage.message.sendtime", 0);
        }
        
        public static void setMessageTime(Long time) {
            homePage.putLong("homepage.message.sendtime", time);
        }
        
        public static String getMessageUser() {
            return homePage.getSp().getString("homepage.message.user", "");
        }
        
        public static void setMessageUser(String user) {
            homePage.putString("homepage.message.user", user);
        }
        
        public static String getMessageAvatar() {
            return homePage.getSp().getString("homepage.message.avatar", "");
        }
        
        public static void setMessageAvatar(String avatar) {
            homePage.putString("homepage.message.avatar", avatar);
        }
        
        public static String getMessageContent() {
            return homePage.getSp().getString("homepage.message.content", "");
        }
        
        public static void setMessageContent(String content) {
            homePage.putString("homepage.message.content", content);
        }
    }
}
